#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h>
#include<string.h>

#define FIFO "publicfifo"
#define FIFO1 "privatefilo1"
#define FIFO2 "privatefifo2"

int main(int argc,char *argv[])
{
    FILE *fp;
    FILE *fp1;
    FILE *fp2;
    int temp;
    char readbuf[100];
    char writebuf[100]="\0";
    char buf[100];

    if(argc<2)
    {
        printf("not input argv[1]\n");
        exit(1);
    }

    temp=atoi(argv[1]);
    if(temp==1)
    {
        while(1)
        {
            memset(writebuf,'\0',100);
            if((fp=fopen(FIFO,"w"))==NULL)
            {
                printf("open FIFO failed.\n");
                exit(1);
            }
            writebuf[0]='1';
            scanf("%s",buf);
            strcat(buf,"\n");
		    strcat(writebuf,buf);
            if(fputs(writebuf,fp)==EOF)
            {
                printf("write to FIFO failed.\n");
                exit(1);
            }
            fclose(fp);
            memset(readbuf,'\0',100);
            if((fp1=fopen(FIFO1,"r"))==NULL)
            {
                printf("open FIFO1 failed.\n");
                exit(1);
            }
            if(fgets(readbuf,sizeof(readbuf),fp1)!=NULL)
            {
                printf("the string from privatefifo1 is\n%s\n\n",readbuf);
                fclose(fp1);
            }
        }
    }
    else if(temp==2)
    {
        while(1)
        {
            memset(writebuf,'\0',100);
            if((fp=fopen(FIFO,"w"))==NULL)
            {
                printf("open FIFO failed.\n");
                exit(1);
            }
            writebuf[0]='2';
            scanf("%s",buf);
            strcat(buf,"\n");
		    strcat(writebuf,buf);
            if(fputs(writebuf,fp)==EOF)
            {
                printf("write to FIFO failed.\n");
                exit(1);
            }
            fclose(fp);
            memset(readbuf,'\0',100);
            if((fp2=fopen(FIFO2,"r"))==NULL)
            {
                printf("open FIFO2 failed.\n");
                exit(1);
            }
            if(fgets(readbuf,sizeof(readbuf),fp2)!=NULL)
            {
                printf("the string from privatefifo2 is\n%s\n\n",readbuf);
                fclose(fp2);
            }
        }
    }
}